const crypto = require('crypto');
const sqlite3 = require('sqlite3').verbose();
const readline = require('readline');
const CryptoJS = require("crypto-js");
const net = require('net');
const WebSocket = require('ws');
const axios = require('axios');
const https = require('https');
const fs = require('fs');
const path = require('path');
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const moment = require('moment');

var qs = require('qs');

const adapter = new FileSync('log.json');
const db = low(adapter);
db.defaults({ logs: [] }).write();

const adapter1 = new FileSync('config.json');
const db1 = low(adapter1);
db1.defaults({ configs: {} }).write();

// 创建 SQLite 数据库连接
const dbPath = path.join(__dirname, 'history.db');
const db2 = new sqlite3.Database(dbPath);

// 创建 logs 表
db2.serialize(() => {
    db2.run(`
        CREATE TABLE IF NOT EXISTS logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            mapData TEXT,
            response TEXT,
            formattedTime TEXT
        )
    `);
});
const express = require('express');
const app = express();
const cors = require('cors');
const { time, error, log, info } = require('console');
const { type } = require('os');
const { Agent } = require('http');
app.use(express.json());
app.use(cors());

const publicPath8 = path.join(__dirname, './file/jtHome.html');

const publicPath2 = path.join(__dirname, './file/tiaoshi.html');
const publicPath5 = path.join(__dirname, 'sound');
const publicPath10 = path.join(__dirname, './file/JtLogin.html');
// 提供静态文件服务
app.use('/jtHome', express.static(publicPath8));
app.use('/JtLogin', express.static(publicPath10))


app.use('/tiaoshi', express.static(publicPath2));
app.use('/sound', express.static(publicPath5));
// 获取日志接口
app.get('/logs', (req, res) => {
    const page = parseInt(req.query.page) || 1; // 默认页码为1
    const limit = parseInt(req.query.limit) || 10; // 默认每页10条记录
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    // 获取总记录数
    db2.get(`SELECT COUNT(*) AS total FROM logs`, (err, countResult) => {
        if (err) {
            return res.status(500).json({ success: false, message: 'Database error' });
        }

        const total = countResult.total;

        // 分页查询
        db2.all(`SELECT * FROM logs ORDER BY formattedTime DESC LIMIT ${limit} OFFSET ${startIndex}`, (err, rows) => {
            if (err) {
                return res.status(500).json({ success: false, message: 'Database error' });
            }

            const results = {};

            if (endIndex < total) {
                results.next = {
                    page: page + 1,
                    limit: limit
                };
            }

            if (startIndex > 0) {
                results.previous = {
                    page: page - 1,
                    limit: limit
                };
            }

            results.results = rows;
            results.total = total;
            res.json(results);
        });
    });
});
app.get('/failLogs', (req, res) => {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    // 获取所有请求失败的数据的总数 847517582   
    db2.get(`SELECT COUNT(*) AS total FROM logs WHERE response != '请求成功'`, (err, countResult) => {
        if (err) {
            return res.status(500).json({ success: false, message: 'Database error' });
        }

        const total = countResult.total;

        // 分页查询请求失败的数据
        db2.all(`SELECT * FROM logs WHERE response != '请求成功' ORDER BY formattedTime DESC LIMIT ${limit} OFFSET ${startIndex}`, (err, rows) => {
            if (err) {
                return res.status(500).json({ success: false, message: 'Database error' });
            }

            const results = {};

            if (endIndex < total) {
                results.next = {
                    page: page + 1,
                    limit: limit
                };
            }

            if (startIndex > 0) {
                results.previous = {
                    page: page - 1,
                    limit: limit
                };
            }

            results.results = rows;
            results.total = total;
            results.codes = rows.map(log => JSON.parse(log.mapData).code);

            // 删除所有请求成功的日志
            db2.run(`DELETE FROM logs WHERE response = '请求成功'`, function (err) {
                if (err) {
                    console.error('Error deleting success logs:', err);
                } else {
                    console.log(`Deleted ${this.changes} success logs`);
                }
            });

            res.json(results);
        });
    });
});
// 查询接口
app.get('/logs/selectLog', (req, res) => {
    const code = req.query.code;
    if (!code) {
        return res.status(400).json({ success: false, message: 'Missing code parameter' });
    }
    db2.all(`SELECT * FROM logs WHERE mapData LIKE '%"code":"${code}"%'`, (err, rows) => {
        if (err) {
            return res.status(500).json({ success: false, message: 'Database error' });
        }

        res.json({ success: true, logs: rows });
    });
});


function getMd5(raw) {
    return crypto.createHash('md5').update(raw).digest('hex');
}

// 删除所有日志
app.get('/deleteAllLogs', (req, res) => {
    db2.run(`DELETE FROM logs`, function (err) {
        if (err) {
            return res.status(500).json({ success: false, message: 'Database error' });
        }

        res.json({ success: true, message: `Deleted ${this.changes} rows` });
    });
});
// 极兔登录接口
app.get('/JtLog', async (req, res) => {
    const { account, password, jtWd } = req.query
    console.log(account, password, jtWd, 'req');
    // 参数
    if (jtWd == 123456) {
        await JtLogin(account, password)
        res.json({ code: 200, data: true })
    } else {
        res.json({ code: 403, data: "该网点未授权，请联系授权" })
    }
})
app.get('/JtLog/Infomation', async (req, res) => {
    if (getInformation == null) {
        res.json({ code: 403, info: getInformation })
    } else {
        res.json({ code: 200, info: getInformation })
    }
})
app.post('/JtLog/upload', (req, res) => {
    // 传过来之后根据mode去调用不同方法
    res.json({ code: 200 })
    nowErp = 'JT'
    if (req.body.mode == 5) {
        req.body.data.forEach((item) => {
            pendingDataQueue.push({ body: { code: item, method: req.query.mode } });
            sendPendingData({ code: item, method: req.body.mode, taskCode: req.body.taskCode });
        })
    } else {
        req.body.data.forEach((item) => {
            pendingDataQueue.push({ body: { code: item, method: req.query.mode } });
            sendPendingData({ code: item, method: req.body.mode });
        })
    }
    wss.clients.forEach(async client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send("logMessage")
        }
    });
})

app.listen(3001, () => {
    if (db.get('configs.serialModule').value() === 1) {
        console.log(`目前打开的分拣串口： ${db.get('configs.serialPort').value()}`);
    }
    if (db.get('configs.gdModule').value() === 1) {
        console.log(`目前打开的光电串口： ${db.get('configs.gdPort').value()}`);
    }
});
function getCurrentDateTimeString() {
    const now = new Date();

    // 获取年、月、日、时、分、秒
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
    const day = String(now.getDate()).padStart(2, '0');
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const second = String(now.getSeconds()).padStart(2, '0');

    // 拼接成所需的格式
    return `${year}${month}${day}${hour}${minute}${second}`;
}
let getInformation = {}
// 极兔模拟登录
async function JtLogin(account, password) {
    try {
        const body = {
            "password": getMd5(password),
            "account": account,
            "macAddr": ""
        }
        const headers = {
            "Accept": "application/json, text/json, text/x-json, text/javascript, application/xml, text/xml",
            "Accept-Encoding": "gzip, deflate",
            "User-Agent": "RestSharp/106.15.0.0",
            "App-Channel": "Internal Deliver",
            "App-Platform": "Android_com.yunlu.salesman.in",
            "App-Version": "1.0.76",
            "authToken": "",
            "devicefrom": "android",
            "Device-ID": "8de733afb71cf3ae282c90fef4f31c83",
            "Device-Name": "OnePlus HD1910",
            "Device-Version": "Android-22",
            "Connection": "Keep-Alive",
            "Host": "bc.jtexpress.com.cn"
        }
        const res = await axios.post('https://bc.jtexpress.com.cn/bc/in/login', body, { headers })
        getInformation = res.data.data
        console.log(getInformation, 'res');

        // console.log(getMd5(account+password), "getInformation authToken: ");
        // console.log(res);
        // ReachJianScan("JT5326492076239","ZXZB24119201320")

    } catch (error) {
        console.log(error, '登录极兔失败');
    }
}

let signrrr = 0

// 收件扫描   只需要单号
async function ShowJianScan(code, url, parameters, ws, data) {
    try {
        const body = [
            {
                "checkOrderExist": "0",
                "hasDelete": false,
                "hasUpload": false,
                "id": "3",
                "listId": getCurrentDateTimeString(),
                "scanNetworkCity": getInformation.cityDesc,
                "scanNetworkContact": getInformation.loginNetworkMobile,
                "scanNetworkProvince": getInformation.providerDesc,
                "scanNetworkTypeId": String(getInformation.institutionalLevelId),
                "scanNetworkTypeName": getInformation.institutionalLevelDesc,
                "scanPda": "9leuh9dev2hnur1kfxpsbh560euwy1ri",
                "scanTime": getCurrentTime(),
                "userId": getInformation.id,
                "waybillId": code
            }
        ]
        const headers = {
            "Accept": "application/json, text/json, text/x-json, text/javascript, application/xml, text/xml",
            "Accept-Encoding": "gzip, deflate",
            "User-Agent": "RestSharp/106.15.0.0",
            "App-Channel": "Internal Deliver",
            "App-Platform": "Android_com.yunlu.salesman.in",
            "App-Version": "1.0.76",
            "authToken": getInformation.token,
            "devicefrom": "android",
            "Device-ID": "8de733afb71cf3ae282c90fef4f31c83",
            "Device-Name": "OnePlus HD1910",
            "Device-Version": "Android-22",
            "Connection": "Keep-Alive",
            "Host": "bc.jtexpress.com.cn"
        }
        const res = await axios.post('https://bc.jtexpress.com.cn/bc/scanList/uploadExpressCollectionData', body, { headers })
        const logMessage = JSON.stringify({ data, parameters: parameters, response: res.data.msg });
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();
    } catch (error) {
        console.log(code,"code");
        signrrr = signrrr + 1
        console.log(signrrr, "signrrr");
        const logMessage = JSON.stringify({ data, parameters: parameters, response: '网络延时导致传输失败' });
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();
    }
}
// 入仓扫描   也只需要单号
async function JoinCangScan(code, url, parameters, ws, data) {
    try {
        // console.log(getInformation, "getInformation");
        const body = [
            {
                "hasDelete": false,
                "hasUpload": false,
                "id": "6",
                "isProtocol": "0",
                "listId": getCurrentDateTimeString(),
                "salesmanCode": getInformation.staffNo,
                "salesmanId": String(getInformation.id),
                "salesmanName": getInformation.name,
                "scanNetworkCity": getInformation.cityDesc,
                "scanNetworkContact": getInformation.loginNetworkMobile,
                "scanNetworkProvince": getInformation.providerDesc,
                "scanNetworkTypeId": String(getInformation.institutionalLevelId),
                "scanNetworkTypeName": getInformation.institutionalLevelDesc,
                "scanPda": "9leuh9dev2hnur1kfxpsbh560euwy1ri",
                "scanTime": getCurrentTime(),
                "type": "0",
                "userId": getInformation.id,
                "waybillId": code,
                "weight": 0.0,
                "weightFlag": "1"
            }
        ]
        const headers = {
            "Accept": "application/json, text/json, text/x-json, text/javascript, application/xml, text/xml",
            "Accept-Encoding": "gzip, deflate",
            "User-Agent": "RestSharp/106.15.0.0",
            "App-Channel": "Internal Deliver",
            "App-Platform": "Android_com.yunlu.salesman.in",
            "App-Version": "1.0.76",
            "authToken": getInformation.token,
            "devicefrom": "android",
            "Device-ID": "8de733afb71cf3ae282c90fef4f31c83",
            "Device-Name": "OnePlus HD1910",
            "Device-Version": "Android-22",
            "Connection": "Keep-Alive",
            "Host": "bc.jtexpress.com.cn"
        }
        // console.log(headers,"headers");
        const res = await axios.post('https://bc.jtexpress.com.cn/bc/scanList/uploadReceiptData', body, { headers })
        const logMessage = JSON.stringify({ data, parameters: parameters, response: res.data.msg });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();

    } catch (error) {
        const logMessage = JSON.stringify({ data, parameters: parameters, response: '网络延时导致传输失败' });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();
    }
}
// 装车发件扫描  需要填写任务编号和下一站代码
async function ZhuangCarScan(code, url, parameters, ws, data) {
    try {
        // console.log(getInformation, "getInformation");
        const body = [
            {
                "carNumber": "",
                "hasDelete": false,
                "hasUpload": false,
                "id": "1",
                "listId": getCurrentDateTimeString(),
                "nextStopCode": "9028497",
                "nextStopId": "1000703",
                "nextStopName": "眉山彭山区网点",
                "nextStopType": "中心",
                "nextStopTypeId": "335",
                "scanNetworkCity": getInformation.cityDesc,
                "scanNetworkContact": getInformation.loginNetworkMobile,
                "scanNetworkProvince": getInformation.providerDesc,
                "scanNetworkTypeId": String(getInformation.institutionalLevelId),
                "scanNetworkTypeName": getInformation.institutionalLevelDesc,
                "scanPda": "9leuh9dev2hnur1kfxpsbh560euwy1ri",
                "scanTime": getCurrentTime(),
                "scanType": "1",
                "taskCode": "123456789",  //  任务编号
                "transportTypeCode": "02",
                "transportTypeId": "22",
                "transportTypeName": "公路运输",
                "userId": getInformation.id,
                "waybillId": code,
                "waybillInputType": "2"
            }
        ]
        const headers = {
            "Accept": "application/json, text/json, text/x-json, text/javascript, application/xml, text/xml",
            "Accept-Encoding": "gzip, deflate",
            "User-Agent": "RestSharp/106.15.0.0",
            "App-Channel": "Internal Deliver",
            "App-Platform": "Android_com.yunlu.salesman.in",
            "App-Version": "1.0.76",
            "authToken": getInformation.token,
            "devicefrom": "android",
            "Device-ID": "8de733afb71cf3ae282c90fef4f31c83",
            "Device-Name": "OnePlus HD1910",
            "Device-Version": "Android-22",
            "Connection": "Keep-Alive",
            "Host": "bc.jtexpress.com.cn"
        }
        // console.log(headers,"headers");
        const res = await axios.post('https://bc.jtexpress.com.cn/bc/scanList/uploadReceiptData', body, { headers })
        const logMessage = JSON.stringify({ data, parameters: parameters, response: res.data.msg });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();

    } catch (error) {
        const logMessage = JSON.stringify({ data, parameters: parameters, response: '网络延时导致传输失败' });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();
    }
}
// 收入发扫描  需要任务编号和下一站代码

// 到件扫描 只需要单号 以及任务编号
async function ReachJianScan(code, taskCode, url, parameters, ws, data) {


    try {
        // console.log(getInformation, "getInformation");
        const body = [
            {
                "carNumber": "",
                "hasDelete": false,
                "hasUpload": false,
                "id": "3",
                "listId": getCurrentDateTimeString(),
                "networkId": String(getInformation.networkId),
                "scanNetworkCity": getInformation.cityDesc,
                "scanNetworkContact": getInformation.loginNetworkMobile,
                "scanNetworkProvince": getInformation.providerDesc,
                "scanNetworkTypeId": String(getInformation.institutionalLevelId),
                "scanNetworkTypeName": getInformation.institutionalLevelDesc,
                "scanPda": "9leuh9dev2hnur1kfxpsbh560euwy1ri",
                "scanTime": getCurrentTime(),
                "scanType": "1",
                "scanTypeCode": "92",
                "taskCode": taskCode,
                "transportTypeCode": "02",
                "transportTypeId": "22",
                "transportTypeName": "公路运输",
                "userId": String(getInformation.id),
                "waybillId": code,
                "waybillInputType": "2",
                "weight": 0.01,
                "weightFlag": "1"
            }
        ]
        const headers = {
            "Accept": "application/json, text/json, text/x-json, text/javascript, application/xml, text/xml",
            "Accept-Encoding": "gzip, deflate",
            "User-Agent": "RestSharp/106.15.0.0",
            "App-Channel": "Internal Deliver",
            "App-Platform": "Android_com.yunlu.salesman.in",
            "App-Version": "1.0.76",
            "authToken": getInformation.token,
            "devicefrom": "android",
            "Device-ID": "8de733afb71cf3ae282c90fef4f31c83",
            "Device-Name": "OnePlus HD1910",
            "Device-Version": "Android-22",
            "Connection": "Keep-Alive",
            "Host": "bc.jtexpress.com.cn"
        }
        // console.log(headers,"headers");
        const res = await axios.post('https://bc.jtexpress.com.cn/bc/scanList/uploadReceiptData', body, { headers })
        const logMessage = JSON.stringify({ data, parameters: parameters, response: res.data.msg });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();

    } catch (error) {
        const logMessage = JSON.stringify({ data, parameters: parameters, response: '网络延时导致传输失败' });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();
    }
}
//  派件扫描  只需要单号
async function SendJianScan(code, url, parameters, ws, data) {
    try {
        // console.log(getInformation, "getInformation");
        const body = [
            {

                "deliveryBy": String(getInformation.id),
                "deliveryCode": getInformation.staffNo,
                "deliveryMobile": getInformation.loginNetworkMobile,
                "deliveryName": getInformation.name,
                "hasDelete": false,
                "hasUpload": false,
                "id": "1",
                "listId": getCurrentDateTimeString(),
                "scanNetworkCity": getInformation.cityDesc,
                "scanNetworkContact": getInformation.loginNetworkMobile,
                "scanNetworkProvince": getInformation.providerDesc,
                "scanNetworkTypeId": String(getInformation.institutionalLevelId),
                "scanNetworkTypeName": getInformation.institutionalLevelDesc,
                "scanPda": "9leuh9dev2hnur1kfxpsbh560euwy1ri",
                "scanSourceCode": "10",
                "scanSourceName": "系统生成",
                "scanTime": getCurrentTime(),
                "userId": String(getInformation.id),
                "waybillId": code
            }
        ]
        console.log(body[0]);

        const headers = {
            "Accept": "application/json, text/json, text/x-json, text/javascript, application/xml, text/xml",
            "Accept-Encoding": "gzip, deflate",
            "User-Agent": "RestSharp/106.15.0.0",
            "App-Channel": "Internal Deliver",
            "App-Platform": "Android_com.yunlu.salesman.in",
            "App-Version": "1.0.76",
            "authToken": getInformation.token,
            "devicefrom": "android",
            "Device-ID": "8de733afb71cf3ae282c90fef4f31c83",
            "Device-Name": "OnePlus HD1910",
            "Device-Version": "Android-22",
            "Connection": "Keep-Alive",
            "Host": "bc.jtexpress.com.cn"
        }
        // console.log(headers,"headers");
        const res = await axios.post('https://bc.jtexpress.com.cn/bc/scanList/uploadReceiptData', body, { headers })
        const logMessage = JSON.stringify({ data, parameters: parameters, response: res.data.msg });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();

    } catch (error) {
        const logMessage = JSON.stringify({ data, parameters: parameters, response: '网络延时导致传输失败' });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();
    }
}
// 签收扫描   需要选择签收类型
async function ArriveJainScan(code, url, parameters, ws, data) {
    try {
        // console.log(getInformation, "getInformation");
        const body = [
            {
                "deliveryMobile": getInformation.loginNetworkMobile,
                "listId": getCurrentDateTimeString(),
                "scanNetworkCity": getInformation.cityDesc,
                "scanNetworkContact": getInformation.loginNetworkMobile,
                "scanNetworkProvince": getInformation.providerDesc,
                "scanNetworkTypeId": String(getInformation.institutionalLevelId),
                "scanNetworkTypeName": getInformation.institutionalLevelDesc,
                "scanPda": "9leuh9dev2hnur1kfxpsbh560euwy1ri",
                "scanTime": getCurrentTime(),
                "signCode": "1",
                "signId": "70",
                "signName": "本人签收",
                "signer": getInformation.name,
                "waybillId": code
            }
        ]
        const headers = {
            "Accept": "application/json, text/json, text/x-json, text/javascript, application/xml, text/xml",
            "Accept-Encoding": "gzip, deflate",
            "User-Agent": "RestSharp/106.15.0.0",
            "App-Channel": "Internal Deliver",
            "App-Platform": "Android_com.yunlu.salesman.in",
            "App-Version": "1.0.76",
            "authToken": getInformation.token,
            "devicefrom": "android",
            "Device-ID": "8de733afb71cf3ae282c90fef4f31c83",
            "Device-Name": "OnePlus HD1910",
            "Device-Version": "Android-22",
            "Connection": "Keep-Alive",
            "Host": "bc.jtexpress.com.cn"
        }
        // console.log(headers,"headers");
        const res = await axios.post('https://bc.jtexpress.com.cn/bc/scanList/uploadReceiptData', body, { headers })
        const logMessage = JSON.stringify({ data, parameters: parameters, response: res.data.msg });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();

    } catch (error) {
        const logMessage = JSON.stringify({ data, parameters: parameters, response: '网络延时导致传输失败' });
        ws.send("logMessage");
        logQueue.push(JSON.parse(logMessage));
        processLogQueue();
    }
}

function generateDataBean(req_time) {
    // 将 req_time 转换为时间戳（毫秒）
    const currentVersion = moment(req_time, 'YYYY-MM-DD HH:mm:ss').valueOf();
    // 构建 dataBean 对象
    const dataBean = {
        currentVersion: currentVersion.toString()
    };
    // 将 dataBean 转换为 JSON 字符串
    // const _data = JSON.stringify(dataBean, null, 0).replace(/,/g, ', ').replace(/:/g, ': ');
    const _data = `{\"currentVersion\":\"${dataBean.currentVersion}\"}`
    return { _data, dataBean };
}

let logQueue = [];
let processingQueue = false;

// let nowSerial = ''
// 数据库1 是否是中通字段  这个代表可中通的端口  是的话在tcp中执行中通的逻辑
let isZT = db1.get("isZT").value()
// 当前对接的erp控制字段
let nowErp = ''
async function processLogQueue() {
    if (processingQueue) return; // 如果已经在处理队列，则直接返回
    processingQueue = true;
    while (logQueue.length > 0) {
        const logMessage = logQueue.shift();
        // console.log(logMessage, 'logMessage');
        try {
            await insertLog(logMessage).then(res => {
            });
        } catch (error) {
            console.error('Error inserting log:', error);
        }
    }

    processingQueue = false;
}
async function sendSignedRequest(url, parameters, ws, data) {
    if (nowErp === 'JT') {
        if (data.method == 1) {
            // 收件扫描
            await ShowJianScan(data.code, url, parameters, ws, data)
        }
        if (data.method == 2) {
            // 入仓扫描
            await JoinCangScan(data.code, url, parameters, ws, data)
        }
        if (data.method == 3) {
            // 装车发件扫描
        }
        if (data.method == 4) {
            // 收入发扫描
        }
        if (data.method == 5) {
            // 到件扫描
            await ReachJianScan(data.code, data.taskCode, url, parameters, ws, data)
        }
        if (data.method == 6) {
            // 派件扫描
            await SendJianScan(data.code, url, parameters, ws, data)
        }
        if (data.method == 7) {
            // 签收扫描
            await ArriveJainScan(data.code, url, parameters, ws, data)
        }
    }
    else {
        console.log('看到这里请联系IT人员');
    }
}
function insertLog(logMessage) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, 1000);
    });
}
let pendingDataQueue = [];

const wss = new WebSocket.Server({ port: 3000 });
wss.on('connection', (ws) => {
    // console.log('WebSocket client connected');
    sendPendingData();

    let heartbeatInterval = setInterval(() => {
        if (ws.readyState === WebSocket.OPEN) {
            ws.send('ping');
        }
    }, 1000); // 每 30 秒发送一次心跳

    ws.on('message', (message) => {
        // console.log(message, '66666666666666666666');
        if (message instanceof Buffer) {
            message = JSON.parse(message.toString('utf-8'));
        }

        if (message.info === 'pong') {
            // console.log('1111111111');
        } else {
            // console.log('Received message from WebSocket client:', message);
        }
        if (message.type === 'guntong') {
            // console.log('收到数据', message.value, message.port);
            // 先更改串口  然后再去发指令
            db.set("configs.serialPort", message.port).write()
            db.set("ztOnePointFour.port", message.port).write()
            db.set("onePointFour.port", message.port).write()
            sendDataToSerialPort(hexStringToBufferOneLine(message.value));
        }
    });

    ws.on('close', () => {
        // console.log('WebSocket client disconnected');
        clearInterval(heartbeatInterval);
    });

    ws.on('error', (err) => {
        // console.error('WebSocket error:', err);
        clearInterval(heartbeatInterval);
    });
});

// 各erp系统称重回传业务方法
async function sendPendingData(data) {
    wss.clients.forEach(async client => {
        if (client.readyState === WebSocket.OPEN) {
            while (pendingDataQueue.length > 0) {
                if (nowErp === 'JT') {
                    // url = db1.get('configs.XFWL.url').value()
                    const params = pendingDataQueue.shift();
                    await sendSignedRequest(url = '', parameters = params, client, data)
                }
                else {
                    console.log('后续将会扩展其他erp系统');
                }
            }
        }
    });
}

function hexStringToBufferOneLine(hex) {
    return Buffer.from(hex.replace(/[^0-9a-fA-F]/g, ''), 'hex');
}

// 格式化当前时间
function getCurrentTime() {
    const currentTime = new Date();
    const year = currentTime.getFullYear();
    const month = String(currentTime.getMonth() + 1).padStart(2, '0');
    const day = String(currentTime.getDate()).padStart(2, '0');
    const hours = String(currentTime.getHours()).padStart(2, '0');
    const minutes = String(currentTime.getMinutes()).padStart(2, '0');
    const seconds = String(currentTime.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 数据库写入方法  
async function insertLog(logMessage) {
    // const currentTime = new Date();
    const formattedTime = getCurrentTime();

    let mapData = {};
    let response = '';
    if (nowErp === 'JT') {
        const { response: res, parameters, data } = logMessage;
        const { method, ...rest } = data;
        mapData = rest;
        mapData.weight = method;
        response = res;
    }
    else {
        console.log("数据库插入问题");
        return;
    }
    const stmt = db2.prepare("INSERT INTO logs (mapData, response, formattedTime) VALUES (?, ?, ?)");
    stmt.run(JSON.stringify(mapData), response, formattedTime);
    stmt.finalize();
}